import 'dart:async';

import 'package:dio/dio.dart';
import 'package:flutter_app/service/interceptors.dart';

import '../config/service_url.dart';

//Dart中可选参数，在参数外面加个{} post请求
Future request(url, {formData}) async {
  try {
    Response response;
    Dio dio = new Dio();
    dio.interceptors.add(HttpInterceptors());
    //抓包使用
    /*(dio.httpClientAdapter as DefaultHttpClientAdapter).onHttpClientCreate =
        (client) {
      client.findProxy = (uri) {
        return "PROXY 192.168.6.75:8888";
      };
      client.badCertificateCallback =
          (X509Certificate cert, String host, int port) => true; //加上这个才能抓Https
    };*/

    dio.options.contentType = Headers.formUrlEncodedContentType;
    if (formData == null) {
      response = await dio.post("${servicePath[url]}");
    } else {
      response = await dio.post("${servicePath[url]}", data: formData);
    }
    if (response.statusCode == 200) {
      return response.data;
    } else {
      throw Exception("后端接口出现异常");
    }
  } catch (e) {
    return print("ERROR：=========>${e}");
  }
}

//get请求
Future requestGet(url, {formData}) async {
  try {
    Response response;
    Dio dio = new Dio();
    dio.interceptors.add(HttpInterceptors());
    //抓包使用
  /*  (dio.httpClientAdapter as DefaultHttpClientAdapter).onHttpClientCreate =
        (client) {
      client.findProxy = (uri) {
        return "PROXY 192.168.6.75:8888"; //ipconfig 电脑的IP
      };
      client.badCertificateCallback =
          (X509Certificate cert, String host, int port) => true; //加上这个才能抓Https
    };*/
    dio.options.contentType = Headers.formUrlEncodedContentType;
    if (formData == null) {
      response = await dio.get("${servicePath[url]}");
    } else {
      response =
          await dio.get("${servicePath[url]}", queryParameters: formData);
    }
    if (response.statusCode == 200) {
      return response.data;
    } else {
      // toast("后端接口出现异常");
      throw Exception("后端接口出现异常");
    }
  } catch (e) {
    return print("ERROR：=========>${e}");
  }
}
